package org.answer.controller;


import org.answer.constant.MessageConstant;
import org.answer.entity.PageResult;
import org.answer.entity.QueryPageBean;
import org.answer.entity.Result;
import org.answer.pojo.Member;
import org.answer.service.MemberService;
import org.answer.utils.DateUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.List;

/**
 * 会员管理
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Reference
    private MemberService memberService;

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult = memberService.pageQuery(queryPageBean);
        return pageResult;
    }

    /**
     * 通过id删除用户
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    public Result delete(Integer id){
        try {
            //删除
            memberService.delete(id);
            return new Result(true, MessageConstant.DELETE_MEMBER_SUCCESS);
        }  catch (RuntimeException e) {
            e.printStackTrace();
            return new Result(false, "该用户有预约信息，禁止删除");
        }catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_MEMBER_FAIL);
        }
    }

    /**
     * 添加用户
     * @param member
     * @return
     */
    @RequestMapping("/add")
    public Result add(@RequestBody Member member){
        try {
            //设置当前时间
            Date date = new Date();
            member.setRegTime(date);
            //设置默认密码
            member.setPassword("1234");
            //添加
            memberService.add(member);
            return new Result(true, MessageConstant.ADD_MEMBER_SUCCESS);
        } catch (RuntimeException e) {
//            e.printStackTrace();  不用输出
            return new Result(false, MessageConstant.FILENAME_EXIST);
        }catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_MEMBER_FAIL);
        }
    }

    @RequestMapping("/update")
    public Result update(@RequestBody Member member){
        try {
            //添加
            memberService.update(member);
            return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
        }
    }

    @RequestMapping("/memberExcel")
    public Result memberExcel(HttpServletRequest request, HttpServletResponse response) {
        try {
            //list里面有所有的数据  每一个map就是一个用户的数据

            //获取用户的数据
            List<Member> data = memberService.memberExcel();

            //获取文件的磁盘绝对路径    File.separator 表示 文件夹的分割父   linux 是 /  windows是 \\ 这个可以根据系统动态获取
            String path = request.getSession().getServletContext().getRealPath("template")
                    + File.separator + "member.xlsx";


            //获取文件模板（工作蒲）
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(path)));

            //获取工作表  第一张表
            XSSFSheet sheet = workbook.getSheetAt(0);

            //获取到报表的详细数据

            int num = 3;

            //获取每一个用户的数据
            for (Member member : data) {
                //档案编号

                XSSFRow row = sheet.createRow(num);
                row.createCell(0).setCellValue(member.getFileNumber());
                //姓名
                row.createCell(1).setCellValue(member.getName());
                //性别
                row.createCell(2).setCellValue(member.getSex());
                //电话号码
                row.createCell(3).setCellValue(member.getPhoneNumber());
                //身份证号码
                row.createCell(4).setCellValue(member.getIdCard());
                //注册时间
                row.createCell(5).setCellValue(DateUtils.parseDate2String(member.getRegTime()));
                //邮箱
                row.createCell(6).setCellValue(member.getEmail());
                //生日
                row.createCell(7).setCellValue(DateUtils.parseDate2String(member.getBirthday()));
                // 备注
                row.createCell(8).setCellValue(member.getRemark());
                num++;
            }
            //通过流，将数据响应给客户端
            ServletOutputStream outputStream = response.getOutputStream();

            //通过响应头告诉浏览器下载的内容格式
            //表示下载的是 微软的 excel 格式
            response.setContentType("application/vnd.ms-excel");
            //以附件格式下载，下载名为 member.xlsx
            response.setHeader("content-Disposition", "attachment;filename=member.xlsx");
            //通过流，将文件写到流里面
            workbook.write(outputStream);
            //关流，刷新
            outputStream.flush();
            outputStream.close();
            workbook.close();

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

}
